package com.inhg.inhg_android.net.catchers;

import com.inhg.inhg_android.BaseApplication;
import com.inhg.inhg_android.net.error.ApiException;
import com.inhg.inhg_android.net.error.NetWorkException;
import com.inhg.inhg_android.net.model.BaseModel;
import com.inhg.inhg_android.utils.NetUtils;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * Created by ZengYan on 2017/7/27.
 * Email : 810989881@qq.com
 *
 * @decs :
 */

public class ExceptrionCatcher<T extends BaseModel> implements ObservableTransformer<T, T> {


    @Override
    public ObservableSource<T> apply(@NonNull Observable<T> observable) {
        return observable
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        if (!NetUtils.isNetworkAvailable(BaseApplication.getContext())) {
                            /*如果网络不可用*/
                            throw new NetWorkException("网络不可用");
                        }
                    }
                }).doAfterNext(new Consumer<T>() {
                    @Override
                    public void accept(@NonNull T t) throws Exception {
//                        如果是业务报错
                        if (t.getCode() != 200) {
                            throw new ApiException(t.getCode(), t.getMessage());
                        }
                    }
                });
    }
}
